import 'dart:math';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_single_choice_button_widget/common_single_choice_button_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/relative_stu/select_relative_stu_list_view_model.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../../app_main.dart';
import 'bean/relative_stu_list_response_bean.dart';

/// 选择关联学员
class SelectRelativeStuListPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SelectRelativeStuListPage";

  final List<String> selectedList;
  final List<StudentInfoBean> studentInfo;
  final GroupListBean stuListBean;
  final String pfuid;
  // final bool isShowPage;
  const SelectRelativeStuListPage({Key key, this.selectedList, this.stuListBean, this.pfuid, this.studentInfo})
      : super(key: key);

  @override
  _SelectRelativeStuListPageState createState() =>
      _SelectRelativeStuListPageState();

  ///跳转方法
  static Future<Map>navigatorPush(
      BuildContext context, List<String> selectedList, GroupListBean stuListBean,String pfuid,{List<StudentInfoBean> studentInfo}) {
    return RouterUtils.routeForFutureResult<Map>(
      context,
      SelectRelativeStuListPage(selectedList: selectedList,stuListBean: stuListBean,pfuid:pfuid,studentInfo:studentInfo),
      routeName: SelectRelativeStuListPage.ROUTER,
    );
  }
}

class _SelectRelativeStuListPageState
    extends BasePagerState<StuBean, SelectRelativeStuListPage>
    with VgPlaceHolderStatusMixin {
  SelectRelativeStuListViewModel _viewModel;

  //选择的学员id
  List<String> selectStuIds;

  List<String> finalStuIds = List<String>();

  bool isSelected;

  bool isSelectedFuids = true;
  List<StuBean> newAllList;
  @override
  void initState() {
    super.initState();
    selectStuIds = new List();
    newAllList=List();
    if(widget.selectedList!=null){
      selectStuIds = widget.selectedList??[];
      selectStuIds?.forEach((element) {
        finalStuIds?.add(element);
      });
      // finalStuIds = selectStuIds?.toString();
      //     setState(() { });
    }
    _viewModel = SelectRelativeStuListViewModel(this);
    _viewModel.stuListBean=widget?.stuListBean;
    _viewModel?.refresh();
    setState(() { });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        SizedBox(height: 14),
        CommonSearchBarWidget(
          hintText: "搜索",
          onChanged: (keyword){
            _viewModel.keyword=keyword;
            _viewModel.refresh();
          },
          onSubmitted: (keyword){
            _viewModel.keyword=keyword;
            _viewModel.refresh();
          },
        ),
        Expanded(
          child: MixinPlaceHolderStatusWidget(
              errorOnClick: () => _viewModel?.refresh(),
              emptyOnClick: () => _viewModel?.refresh(),
              child: _toPullRefreshWidget()),
        )
      ],
    );
  }

  Widget _toPullRefreshWidget() {
    // List<StuBean> sList = List();
    //如果data有选中的，则跳到最上面
    //选择时不变
    if(isSelectedFuids){
      if(selectStuIds!=null&&selectStuIds?.length>0&&data!=null&&data?.length>0){
        List<StuBean> newList=List();
        List<String> list = List<String>();
        newAllList?.forEach((newList) {
          list?.add(newList?.fuid);
        });
        for (StuBean element in data) {
          // newAllList?.forEach((newList) {
          if(!(list?.toString()?.contains(element?.fuid))){
            newAllList?.add(element);
          }
          //
          // });

          if (selectStuIds?.contains(element?.fuid)) {
            newList?.insert(0, element);
          }else{
            newList.add(element);
          }

        }
        data=newList;
      }
    }
    return VgPullRefreshWidget.bind(
        state: this,
        viewModel: _viewModel,
        enablePullDown: false,
        child: ListView.separated(
            itemCount: data?.length ?? 0,
            padding: const EdgeInsets.all(0),
            physics: BouncingScrollPhysics(),
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
            itemBuilder: (BuildContext context, int index) {
              if (data == null || data.length <= index) {
                return Container();
              }

              return _listItem(data[index]);
            },
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 0,
              );
            }));
  }

  @override
  void finishRefresh({Duration duration}) {
    setState(() {});
  }

  ///topbar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "关联学员",
      isShowBack: true,
      rightWidget: CommonFixedHeightConfirmButtonWidget(
          isAlive: true,
          width: 48,
          height: 24,
          unSelectBgColor:
          ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
          selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          unSelectTextStyle: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              fontWeight: FontWeight.w600),
          selectedTextStyle: TextStyle(
              color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
          text: "确定",
          onTap: () {
            _toPopSelectedList();
          }
      ),
    );
  }

  void _toPopSelectedList() {
    if ((isEmptyStatus || isErrorStatus || isLoadingStatus)) {
      VgToastUtils.toast(context, "数据加载中～");
      return;
    }
    List<String> _selectStuIds = List<String> ();

      if(UserRepository.getInstance().userData.comUser.roleid=="90"){
        List<String> listSelectIds = List<String> ();
        //所选的学员id与所需要保存的对比/
        //选择的id，studentInfo存在则不变，不存在则保存起来
        widget?.studentInfo?.forEach((element) {
          listSelectIds?.add(element?.fuid);
          if(!(selectStuIds?.contains(element?.fuid))){//如果保存的id没有则加入
            _selectStuIds?.add(element?.fuid);
          }
        });
        // finalStuIds = finalStuIds?.replaceAll("[", "");
        // finalStuIds = finalStuIds?.replaceAll("]", "");
        finalStuIds?.forEach((element) {
          if(listSelectIds?.contains(element?.toString())){
            _selectStuIds?.remove(element);
          }
        });
        selectStuIds?.forEach((element) {
          // if(!(listSelectIds?.contains(element?.toString()))){
          _selectStuIds?.add(element?.toString());
          // }
        });
      }else{
        _selectStuIds = selectStuIds;
      }
    if(StringUtils.isNotEmpty(widget?.pfuid)){
      _viewModel.saveParentUserHttp(context, _selectStuIds ,widget?.pfuid);
    }
    setState(() { });
    Map map={'ids': _selectStuIds, 'name': getShowNames()};
    RouterUtils.pop<Map>(context,result: map);
  }

  Widget _listItem(StuBean data) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        child: _toMainRowWidget(context, data),
        padding: EdgeInsets.symmetric(vertical: 12),
      ),
      onTap: () {
        List<String> list = List<String>();
        newAllList?.forEach((newList) {
          list?.add(newList?.fuid);
        });
        if (selectStuIds.contains(data.fuid)) {
          selectStuIds.remove(data.fuid);

          if(list?.toString()?.contains(data.fuid)){
            StuBean stu = StuBean();
            newAllList?.forEach((element) {
              if(element?.fuid == data.fuid){
                stu = element;
              }
            });
            newAllList?.remove(stu);
          }
        } else {
          selectStuIds.add(data.fuid);
          if(!(list?.toString()?.contains(data.fuid))){
            newAllList?.add(data);
          }
        }
        if((selectStuIds?.length??0)>0)isSelected = true;
        // else isSelected = false;
        isSelectedFuids = false;
        setState(() {});
      },
    );
  }

  Widget _toMainRowWidget(BuildContext context, StuBean itemBean) {
    return Row(
      children: <Widget>[
        // Padding(
        //   padding: const EdgeInsets.symmetric(horizontal: 15),
        //   child: Image(
        //     image: itemBean?.isSelect ?? false
        //         ? AssetImage("images/common_selected_ico.png")
        //         : AssetImage("images/common_unselect_ico.png"),
        //     width: 20,
        //   ),
        // ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: CommonSingleChoiceButtonWidget(
              selectStuIds.contains(itemBean.fuid)
                  ? CommonSingleChoiceStatus.selected
                  : CommonSingleChoiceStatus.unSelect),
        ),
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Container(
            width: 36,
            height: 36,
            child: VgCacheNetWorkImage(
              showOriginEmptyStr(itemBean?.putpicurl) ??
                  showOriginEmptyStr(itemBean?.napicurl ?? "") ??
                  (itemBean?.pictureUrl ?? ""),
              fit: BoxFit.cover,
              imageQualityType: ImageQualityType.middleDown,
              defaultErrorType: ImageErrorType.head,
              defaultPlaceType: ImagePlaceType.head,
            ),
          ),
        ),
        SizedBox(
          width: 10,
        ),
        Container(
          height: 36,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: (VgStringUtils.checkAllEmpty([
              itemBean?.department?.trim(),
              itemBean?.projectname?.trim(),
              itemBean?.city?.trim(),
              itemBean?.classname?.trim(),
              // itemBean?.coursename?.trim(),
            ]))
                ? MainAxisAlignment.center
                : MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  CommonNameAndNickWidget(
                    name: itemBean?.name,
                    nick: itemBean?.nick,
                  ),
                  VgLabelUtils.getRoleLabel(itemBean?.roleid) ?? Container(),
                  _toPhoneWidget(itemBean),
                ],
              ),
              if (!VgStringUtils.checkAllEmpty([
                itemBean?.department?.trim(),
                itemBean?.projectname?.trim(),
                itemBean?.city?.trim(),
                itemBean?.classname?.trim(),
                // itemBean?.coursename?.trim(),
              ]))
                Builder(builder: (BuildContext context) {
                  return CommonConstraintMaxWidthWidget(
                    maxWidth: ScreenUtils.screenW(context) / 2,
                    child: Text(
                      VgStringUtils.getSplitStr([
                        itemBean?.department?.trim(),
                        itemBean?.projectname?.trim(),
                        itemBean?.city?.trim(),
                        itemBean?.classname?.trim(),
                        // itemBean?.coursename?.trim(),
                      ], symbol: "/"),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 12,
                      ),
                    ),
                  );
                }),
            ],
          ),
        ),
        Expanded(
          child: _toColumnWidget(itemBean),
        ),
        SizedBox(
          width: 15,
        )
      ],
    );
  }

  Widget _toPhoneWidget(StuBean itemBean) {
    return Offstage(
      offstage: itemBean.phone == null || itemBean.phone.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(itemBean?.phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  /// 李珊珊添加·未激活 /打卡时间
  /// 分类名称·编号
  _toColumnWidget(StuBean itemBean) {
    if (StringUtils.isNotEmpty(itemBean.type)) {}
    return DefaultTextStyle(
      style: TextStyle(height: 1.2),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          //未激活的
          UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition()?
          (itemBean.isAlive()
              ? Text.rich(TextSpan(children: [
            TextSpan(
                text: '${itemBean.uname??''}添加·',
                style: TextStyle(fontSize: 10, color: VgColors.INPUT_BG_COLOR)),
            TextSpan(
                text: '未激活',
                style: TextStyle(fontSize: 10, color: Color(0xfff95355)))
          ]))
              :
          //激活的显示上次打卡时间
          Text(VgDateTimeUtils.getFormatTimeStr(itemBean.lastPunchTime)??'未打卡',
              style: TextStyle(fontSize: 10, color: VgColors.INPUT_BG_COLOR))
          )
              :Text('${itemBean.uname??''}添加',
              style: TextStyle(fontSize: 10, color: VgColors.INPUT_BG_COLOR)),
          SizedBox(
            height: 5,
          ),
          //分类名称·编号
          Text(
            _getGroupAndIdStr(itemBean.groupName, itemBean.number),
            style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR),
            overflow: TextOverflow.ellipsis,
          )
        ],
      ),
    );
  }

  ///分类名称·编号
  String _getGroupAndIdStr(String groupName, String number) {
    if (StringUtils.isEmpty(groupName) && StringUtils.isEmpty(number)) {
      return null;
    }
    if (StringUtils.isNotEmpty(groupName) && StringUtils.isEmpty(number)) {
      return groupName;
    }
    if (StringUtils.isEmpty(groupName) && StringUtils.isNotEmpty(number)) {
      return number;
    }
    return groupName + "·" + number;
  }

  ///学员名按顿号拼接
  getShowNames() {
    StringBuffer nameText = StringBuffer();
    newAllList.forEach((StuBean element) {
      if (selectStuIds?.contains(element?.fuid)) {
        if(element?.nick!=null && element?.nick!=""){
          nameText..write("${element?.name}/${element?.nick}");
          nameText..write("、");
        }else{
          nameText..write(element?.name);
          nameText..write("、");
        }

      }
    });
    if (nameText.length > 1) {
      return nameText.toString().substring(0, nameText.length - 1);
    } else {
      return nameText.toString();
    }
  }
}
